package com.example.lazyhelper.ui.request;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lazyhelper.*;

import java.util.ArrayList;
import java.util.List;

public class RequestFragment extends Fragment {

    private RequestViewModel mRequestViewModel;             // 碎片的数据包
    private RequestListAdapter mAdapter;                    // 请求列表的显示适配器

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        Log.d("in onCreateView", "ENTER!!!!!");

        List<DataItem> items = getList();

        // 加载碎片布局
        View root = inflater.inflate(R.layout.fragment_request, container, false);

        mRequestViewModel = new ViewModelProvider(this).get(RequestViewModel.class);
        mAdapter = new RequestListAdapter(this.getActivity(), items);

        // 绑定观察碎片的数据
        mRequestViewModel.getItems().observe(getViewLifecycleOwner(), new Observer<List<DataItem>>() {
            @Override
            public void onChanged(@Nullable List<DataItem> list) {
                mAdapter.changeDataSet(list);
                mAdapter.notifyDataSetChanged();
            }
        });

        // 在碎片根视图中找到列表组件
        RecyclerView recyclerView = root.findViewById(R.id.request_list);
        // 设置竖直显示的布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity(),
                LinearLayoutManager.VERTICAL, false);
        // 设置列表的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);

        Log.d("in onCreateView", "EXIT!!!!!");
        return root;
    }

    // In later version, we will get data from the server.
    public List<DataItem> getList() {
        ArrayList<DataItem> list =  new ArrayList<>();
        list.add(new DataItem("沁苑中通求帮", "帮忙带到东十一舍一楼"));
        list.add(new DataItem("东一食堂帮带个烧鹅饭呗", "坐标东十二舍"));
        list.add(new DataItem("南四门求帮领外卖", "送到东十三舍XXX"));
        for (int i = 0; i < 10; i++) {
            list.add(new DataItem("XXXXXX", "XXXXXXXX"));
        }
        return list;
    }


}